package com.luoying.itew.http;

import com.luoying.itew.event.LoginEvent;
import com.luoying.itew.util.LogUtils;

import org.greenrobot.eventbus.EventBus;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 封装之后的回调
 * @param <T>
 */
public abstract class HttpResponseCallBack<T> implements Callback<BaseResponse<T>> {
    private static final String TAG = "HttpResponseCallBack";

    /**
     * 访问成功但是也是业务错误
     *
     * @param message
     */
    public abstract void onFail(String message);

    /**
     * 访问成功并且业务也是成功
     *
     * @param data
     */
    public abstract void onSuccess(T data);

    /**
     * 请求失败
     *
     * @param message
     */
    public abstract void onError(String message);

    @Override
    public void onResponse(Call<BaseResponse<T>> call, Response<BaseResponse<T>> response) {
        if (!response.isSuccessful()|| response.body() == null) {
            onError("");
            return;
        }
        if (response.body().getResultCode() != 0) {
            onFail(response.body().getResultMessage());
            if(response.body().getResultCode()==496&&response.body().getResultMessage().contains("accesss_token")){
                //认为用户账号在其他设备登录
                EventBus.getDefault().post(new LoginEvent(LoginEvent.LOGIN_STATE_SINGLE));
            }
        } else {
            onSuccess(response.body().getResultEntity());
        }
    }

    @Override
    public void onFailure(Call<BaseResponse<T>> call, Throwable t) {
        LogUtils.d(TAG,t.toString());
        onError(t==null?"":t.toString());
    }
}
